package com.flea.hclv.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.flea.hclv.model.dao.HCarAgencyItemMapper;
import com.flea.hclv.model.dao.HCarAgencyMapper;
import com.flea.hclv.model.dao.HCarCalendarMapper;
import com.flea.hclv.model.dao.HCarMapper;
import com.flea.hclv.model.entity.*;
import com.flea.hclv.service.HCarAgencyService;
import com.flea.hclv.util.ServerResponse;
import com.flea.system.bean.FleaPage;
import com.flea.system.platform.session.FleaOrgUtils;
import com.flea.system.utils.FleaStringUtils;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @program: project
 * @description: 车辆下单代办
 * @author: shiliqiang
 * @create: 2019-03-03 15:10
 * @version: 1.0
 */
@Service
public class HCarAgencyServiceImpl implements HCarAgencyService {

    @Autowired
    private HCarCalendarMapper hCarCalendarMapper;
    @Autowired
    private HCarMapper hCarMapper;
    @Autowired
    private HCarAgencyMapper hCarAgencyMapper;
    @Autowired
    private HCarAgencyItemMapper hCarAgencyItemMapper;

    @Override
    public ServerResponse<FleaPage<HCarAgencyItem>> getReserveCarItem(FleaPage<HCar> paging, String carAgencyId) {
        RowBounds rowBounds = new RowBounds(paging.getCurPage(), paging.getPageSize());
        List<HCarAgencyItem> items = hCarAgencyItemMapper.selectByReserveCarIdAndPaging(rowBounds,carAgencyId);
        FleaPage<HCarAgencyItem> fleaPage = new FleaPage<>(items);
        return ServerResponse.createBySuccess(fleaPage);
    }

    @Override
    public ServerResponse<FleaPage<HCar>> getRequireCars(HttpServletRequest request, FleaPage<HCar> paging, String model) {
        HCarAgency reserve = JSONObject.parseObject(model,HCarAgency.class);
        String deptId = FleaOrgUtils.getCurrentUserDeptUuid(request);
        List<HCar> hCars;
//        hCars = hCarMapper.findTypeAndCarNumber(reserve.getCarNumber(), reserve.getCarType(), deptId);
        hCars = hCarMapper.selectByTypeAndCarNumber(reserve.getCarNumber(), reserve.getCarType(), deptId);
        if (CollectionUtils.isEmpty(hCars)) {
            return ServerResponse.createBySuccessMessage("没有找到符合条件的车");
        }
        //查出 使用开始时间 和使用终止时间内的已经预定车;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String st = sdf.format(reserve.getUseDate());
        String end = sdf.format(reserve.getReturnDate());
        List<HCarCalendar> carCalendars = hCarCalendarMapper.selectByTimeAndCarId(hCars, st, end);
        List<String> newCarIds = Lists.newArrayList();
        //排除日程表中查到的车。剩下的车是符合条件的
        if (CollectionUtils.isNotEmpty(carCalendars)) {
//             String calendarCarId = carCalendars.get(0).getCarId();
//             String newCarId;
//             for (HCar car : hCars){
//                 newCarId = car.getId();
//                 if (!calendarCarId.equals(car.getId())){
//                     newCarIds.add(newCarId);
//                 }
//             }
            return ServerResponse.createBySuccessMessage("车的余量不足");
        }
        RowBounds rowBounds = new RowBounds(paging.getCurPage(),paging.getPageSize());
        for (HCar car : hCars){
            newCarIds.add(car.getId());
        }
        hCars = hCarMapper.selectByCarIdsAndPaging(rowBounds, newCarIds);
        if (CollectionUtils.isEmpty(hCars)) {
            return ServerResponse.createBySuccessMessage("没有找到符合条件的车");
        }
        FleaPage<HCar> fleaPage = new FleaPage<>(hCars);
        return ServerResponse.createBySuccess(fleaPage);
    }

    @Override
    public ServerResponse<FleaPage<HCarAgency>> selectAll(HttpServletRequest request, FleaPage<HCarAgency> paging) {
        RowBounds rowBounds = new RowBounds(paging.getCurPage(),paging.getPageSize());
        String currentDeptId = FleaOrgUtils.getCurrentUserDeptUuid(request);
        List<HCarAgency> hCarAgencies = hCarAgencyMapper.selectByDeptId(rowBounds,currentDeptId);
        FleaPage<HCarAgency> fleaPage = new FleaPage<>(hCarAgencies);
        return ServerResponse.createBySuccess(fleaPage);
    }

    @Override
    public ServerResponse<String> addAgency(HttpServletRequest request, String model) throws Exception {
        String userId = FleaOrgUtils.getCurUserUuid(request);
        String currentDeptId = FleaOrgUtils.getCurrentUserDeptUuid(request);
        JSONObject jsonObject = JSON.parseObject(model);
        //预定的内容
        HCarAgency hCarAgency = JSON.parseObject(model, HCarAgency.class);
        Float totalCost = jsonObject.getFloat("totalCost");
        hCarAgency.setTotalCost(totalCost);
        hCarAgency.setProvideDeptId(currentDeptId);
        hCarAgency.setModifyUser(userId);
        hCarAgency.setId(FleaStringUtils.getGenerateUUID());
        //预定的车
        List<HCar> carList = JSON.parseArray(jsonObject.getString("cars"), HCar.class);
        //计算车的日程
        List<Date> dates = HCarReserveServiceImpl.CalculationDate(hCarAgency.getUseDate(), hCarAgency.getReturnDate());
        List<HCarCalendar> carCalendars = Lists.newArrayList();
//        DateFormat FORMATTER = new SimpleDateFormat("yyyy-MM-dd");
        int row;
        List<String> carPlateNumberList = null;
        for (HCar car : carList) {
            String carId = car.getCarId();
            for (Date date : dates) {
                HCarCalendar obj = new HCarCalendar();
                obj.setId(FleaStringUtils.getGenerateUUID());
                obj.setCarId(carId);
                obj.setCreateUser(userId);
                obj.setTodayTime(date);
                carCalendars.add(obj);
            }
            //判断当前时间段车是否正在使用
            List<HCarCalendar> carCalendarsList = hCarCalendarMapper.selectByCarIdAndDates(carId, dates);
            carPlateNumberList = Lists.newArrayList();
            if (CollectionUtils.isNotEmpty(carCalendarsList)) {
                HCar hCar = hCarMapper.selectByPrimaryKey(carId);
                carPlateNumberList.add(hCar.getPlateNumber());
            }
        }
        if (CollectionUtils.isNotEmpty(carPlateNumberList)) {
            StringBuilder sb = new StringBuilder();
            for (String carPlateNumber : carPlateNumberList) {
                sb.append("车牌号：");
                sb.append(carPlateNumber);
                sb.append(",");
                sb.append("在该时间期间可能正在被使用");
            }
            return ServerResponse.createByErrorMessage(sb.toString());
        }


        row = hCarCalendarMapper.insertList(carCalendars);
        if (row == 0) {
            return ServerResponse.createByErrorMessage("添加车日程表记录失败");
        }

        List<HCarAgencyItem> hCarAgencyItems = Lists.newArrayList();
        for (HCar car : carList) {
            HCarAgencyItem item = new HCarAgencyItem();
            item.setCarId(car.getCarId());
            item.setId(FleaStringUtils.getGenerateUUID());
            item.setCreateUser(userId);
            item.setCarAgencyId(hCarAgency.getId());
            item.setDriverId(car.getDriverId());
            hCarAgencyItems.add(item);
        }
        row = hCarAgencyMapper.insertSelective(hCarAgency);
        if (row ==0){
            throw new Exception("添加代办订单失败");
        }
        row = hCarAgencyItemMapper.insertList(hCarAgencyItems);
        if (row == 0) {
            throw new Exception("添加代办项失败");
        }
        return ServerResponse.createBySuccess("操作成功");
    }
}
